<template>
  <div>
    <dialog-content :dialogOptions="dialogOptions || (new Date().getTime())">
      <template slot="dialog-content_content">
        <form-content ref="menuInfoForm" :formOptions="formOptions" :formSource="formSource" @changeHandle="changeHandle">
        </form-content>
      </template>
      <template slot="dialog-content_footer">
        <el-button v-if="add && isAuth('sys:menu:save')" type="primary" v-prevent-re-click
         :size="this.size" @click="submitHandle('save')">保 存</el-button>
        <el-button v-if="change && isAuth('sys:menu:update')" type="primary" v-prevent-re-click
         :size="this.size" @click="submitHandle('edit')">修 改</el-button>
        <el-button v-if="change && isAuth('sys:menu:delete')" type="danger" v-prevent-re-click
         :size="this.size" @click="submitHandle('delete')">删 除</el-button>
        <el-button :size="this.size" @click="dialogOptions.show = false">取 消</el-button>
      </template>
    </dialog-content>
  </div>
</template>

<script>
import { getMenuTreeApi, getMenuInfoApi, saveMenuApi, updateMenuApi, deleteMenuOrPermissionApi } from '@/api/menu'
import DialogContent from '@/components/common/dialog-content'
import FormContent from '@/components/common/form-content'
import Icon from '@/assets/icons'
export default {
  components: {
    DialogContent, FormContent
  },
  props: {
    size: {
      type: String,
      default: 'small'
    },
    nodeId: {
      type: String,
      default: '0'
    }
  },
  data() {
    return {
      dialogOptions: {
        title: '菜单信息',
        show: false,
        modal: true,
        width: '570px',
        height: '380px',
        center: true
      },
      formOptions: {
        inline: true,
        labelPosition: 'right',
        labelWidth: '80px',
        size: this.size
      },
      formSource: {
        operations: [
          {
            name: '名称',
            key: 'name',
            type: 'text',
            width: '170px',
            length: 10
          },
          {
            name: '图标',
            key: 'icon',
            type: 'select',
            width: '135px',
            length: 20,
            list: this.iconReplace()
          },
          {
            name: '',
            key: 'icon',
            type: 'svg',
            width: '25px'
          },
          {
            name: '层级',
            key: 'levelName',
            type: 'text',
            width: '170px',
            disabled: true
          },
          {
            name: '父级名称',
            key: 'parentId',
            type: 'cascader',
            disabled: true,
            cascaderProps: { checkStrictly: true },
            width: '170px',
            cascaderOptions: []
          },
          {
            name: '页面缓存',
            key: 'keepAlive',
            type: 'switch',
            width: '170px'
          },
          {
            name: '导航标签',
            key: 'label',
            type: 'switch',
            width: '170px'
          },
          {
            name: '是否系统',
            key: 'system',
            type: 'switch',
            width: '170px'
          },
          {
            name: '新功能',
            key: 'fresh',
            type: 'switch',
            width: '170px'
          },
          {
            name: '菜单类型',
            key: 'type',
            type: 'select',
            list: [
              { key: '目录', value: 0 },
              { key: '菜单', value: 1 },
              { key: '按钮', value: 2 }
            ]
          },
          { type: 'place', formWidth: '40px' },
          {
            name: '跳转类型',
            key: 'urlType',
            type: 'select',
            width: '170px',
            list: [
              { key: '页面', value: 0 },
              { key: '地址', value: 1 }
            ]
          },
          {
            name: '跳转地址',
            key: 'url',
            type: 'textarea',
            width: '350px',
            length: 200
          },
          {
            name: '权限',
            key: 'permission',
            type: 'textarea',
            width: '350px',
            length: 500
          }
        ],
        ruleForm: {},
        rules: {
          name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
        }
      },
      type: 0 // 0添加菜单1添加权限2菜单查看
    }
  },
  computed: {
    root: {
      get() { return this.$store.getters.root || this.formSource.ruleForm.system }
    },
    add: {
      get() { return this.type === 0 || this.type === 1 }
    },
    change: {
      get() { return this.type === 2 }
    }
  },
  methods: {
    init(type = 0) {
      this.type = type
      if (this.nodeId !== undefined && this.nodeId !== 0 && type === 2) {
        getMenuInfoApi(this.nodeId).then(res => {
          let data = res.data
          this.formSource.ruleForm = {
            id: data.id,
            name: data.name,
            icon: data.icon,
            keepAlive: data.keepAlive,
            label: data.label,
            levelName: this.levelReplace(data.level),
            parentId: data.parentId,
            permission: data.permission,
            system: data.system,
            fresh: data.fresh,
            type: data.type,
            urlType: data.urlType,
            url: data.url
          }
        }).then(res => {
          this.getMenuTree()
          this.controlInit(type)
          this.flushForm(this)
        })
      } else {
        this.formSource.ruleForm = {
          id: '0',
          name: '',
          icon: '',
          keepAlive: false,
          label: false,
          parentId: this.nodeId,
          permission: '',
          system: false,
          fresh: false,
          type: this.type === 1 ? 2 : 0,
          urlType: 0,
          url: ''
        }
        this.getMenuTree()
        this.controlInit(type)
        this.flushForm(this)
      }
    },
    flushForm(target) {
      if (target.$refs.menuInfoForm === undefined) {
        target.$nextTick(() => {
          target.$refs.menuInfoForm.init()
        })
      } else {
        if (this.type !== 2) {
          target.$refs.menuInfoForm.init()
        } else {
          target.$refs.menuInfoForm.update()
          target.$refs.menuInfoForm.clearValidate()
        }
      }
    },
    changeHandle(obj) {
      let _item = obj.backData
      if (_item.key !== 'parentId') {
        return
      }
      let roleTreeValues = this.formSource.ruleForm[_item.key]
      if (roleTreeValues === undefined || roleTreeValues.length === 0) {
        this.formSource.ruleForm.parentId = 0
        return
      }
      let roleTreeOptions = this.formSource.operations[obj._index].cascaderOptions
      let targetRoleTreeIndex = roleTreeValues.length - 1
      let item = this.treeRetrieval(roleTreeOptions, 'value', roleTreeValues[targetRoleTreeIndex], 'children')
      this.formSource.ruleForm.parentId = item.value
    },
    getMenuTree() {
      getMenuTreeApi().then(res => {
        this.formSource.operations.forEach(item => {
          if (item.key === 'parentId') {
            item.cascaderOptions = this.treeFormat(res.data, 'id', 'name', 'subMenus')
            this.formSource.ruleForm.parentId = this.cascaderSuperior(res.data, false, 'subMenus', this.formSource.ruleForm.parentId)
          }
        })
      })
    },
    levelReplace(level = 1) {
      let levels = {
        1: '一级',
        2: '二级',
        3: '三级',
        4: '四级',
        5: '五级',
        6: '六级',
        7: '七级',
        8: '八级',
        9: '九级',
        10: '十级'
      }
      return levels[level]
    },
    iconReplace() {
      let icons = []
      Icon.getNameList().forEach(item => {
        icons.push({ key: item, value: item })
      })
      return icons
    },
    initHeight() {
      if (this.type === 0) {
        return 350
      } else if (this.type === 1) {
        return 210
      } else if (this.type === 2) {
        return 380
      }
    },
    dynamicHeight() {
      let height = this.dialogOptions.height
      height = height.substr(0, height.length - 2)

      let initHeight = this.initHeight()
      height = initHeight
      this.dialogOptions.height = height + 'px'
    },
    controlInit(type) {
      this.dynamicHeight()

      this.formSource.operations.forEach(item => {
        if (type === 0 || type === 1) {
          item.disabled = false
        } else if (type === 2) {
          if (this.root) {
            if (item.key === 'levelName') {
              item.disabled = true
            } else {
              item.disabled = false
            }
          } else {
            item.disabled = true
          }
        }

        if (item.key === 'url' || item.key === 'urlType' || item.key === 'icon' || item.key === 'keepAlive' || item.key === 'label') {
          if (type === 0 || type === 2) {
            item.show = true
          } else {
            item.show = false
          }
        }

        if (item.key === 'levelName' || item.key === 'fresh') {
          if (type === 2) {
            item.show = true
          } else {
            item.show = false
          }
        }

        if (item.key === 'type') {
          if (type === 0 || type === 2) {
            item.list = [
              { key: '目录', value: 0 },
              { key: '菜单', value: 1 }
            ]
          } else {
            item.list = [{ key: '按钮', value: 2 }]
          }
        }
      })
    },
    submitHandle(type = '') {
      if (type === '') return false
      if (!this.$refs.menuInfoForm.submitForm()) return false

      let parentId = this.formSource.ruleForm.parentId
      if (parentId && parentId instanceof Array) {
        this.formSource.ruleForm.parentId = parentId.length === 0 ? 0 : parentId[parentId.length - 1]
      }

      if (type === 'save') {
        saveMenuApi(this.formSource.ruleForm).then(res => {
          this.$message({
            message: '添加成功',
            type: 'success',
            duration: 1500
          })
          this.dialogOptions.show = false
          if (this.type === 0) {
            this.$emit('flush')
          } else {
            this.$emit('flushPermissions')
          }
        }).catch(() => {
          this.$message({
            message: '添加失败',
            type: 'error',
            duration: 1500
          })
        })
      } else if (type === 'edit' && this.formSource.ruleForm.id !== '0') {
        updateMenuApi(this.formSource.ruleForm).then(res => {
          this.$message({
            message: '修改成功',
            type: 'success',
            duration: 1500
          })
          this.dialogOptions.show = false
          this.$emit('flush')
        }).catch(() => {
          this.$message({
            message: '修改失败',
            type: 'error',
            duration: 1500
          })
        })
      } else if (type === 'delete' && this.formSource.ruleForm.id !== '0') {
        deleteMenuOrPermissionApi(this.formSource.ruleForm.id).then(res => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1500
          })
          this.dialogOptions.show = false
          this.$emit('flush')
        }).catch(() => {
          this.$message({
            message: '删除失败',
            type: 'error',
            duration: 1500
          })
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
